package com.ruoyi.system.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Employee;
import com.ruoyi.system.service.IEmployeeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 培训人员管理Controller
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@RestController
@RequestMapping("/employeeManagement/employeeManagement")
public class EmployeeController extends BaseController
{
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ISysDeptService deptService;
    /**
     * 查询培训人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:list')")
    @GetMapping("/list")
    public TableDataInfo list(Employee employee)
    {
        logger.info("接收到的查询参数: {}", employee);
        startPage();
        List<Employee> list = employeeService.selectEmployeeList(employee);
        return getDataTable(list);
    }

    /**
     * 导入培训人员数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<Employee> excelUtil = new ExcelUtil<>(Employee.class);
        List<Employee> employeeList = excelUtil.importExcel(file.getInputStream());
        String operName = getUsername();
        // 注意：这里需要在IEmployeeService中添加importEmployee方法
        String message = employeeService.importEmployee(employeeList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<Employee> util = new ExcelUtil<Employee>(Employee.class) {
            @Override
            public void init(List<Employee> list, String sheetName, String title, Excel.Type type) {
                super.init(list, sheetName, title, type);
                if (type == Excel.Type.IMPORT) {
                    // 获取所有部门
                    List<SysDept> depts = deptService.selectDeptList(new SysDept());
                    List<String> deptNames = new ArrayList<>();
                    for (SysDept dept : depts) {
                        if (dept.getDeptName() != null && !dept.getDeptName().isEmpty()) {
                            deptNames.add(dept.getDeptName());
                        }
                    }

                    try {
                        // 获取工作表
                        Field sheetField = ExcelUtil.class.getDeclaredField("sheet");
                        sheetField.setAccessible(true);
                        Sheet sheet = (Sheet) sheetField.get(this);

                        // 为性别列添加下拉框 (假定性别在第4列，索引为3)
                        String[] genders = {"男", "女"};
                        this.setPromptOrValidation(sheet, genders, "请选择性别", 1, 1000, 3, 3);

                        // 为部门名称列添加下拉框 (假定部门名称在第7列，索引为6)
                        if (!deptNames.isEmpty()) {
                            String[] deptArray = deptNames.toArray(new String[0]);
                            if (deptArray.length > 15 || String.join("", deptArray).length() > 255) {
                                // 如果下拉数大于15或字符串长度大于255，则使用隐藏sheet方式
                                this.setXSSFValidationWithHidden(sheet, deptArray, "请选择部门", 1, 1000, 4, 4);
                            } else {
                                // 提示信息或只能选择不能输入的列内容
                                this.setPromptOrValidation(sheet, deptArray, "请选择部门", 1, 1000, 4, 4);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        util.importTemplateExcel(response, "培训人员数据导入模板");
    }

    /**
     * 导出培训人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:export')")
    @Log(title = "培训人员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Employee employee)
    {
        List<Employee> list = employeeService.selectEmployeeList(employee);
        // 为每个员工设置序号，并确保性别显示为"男"/"女"而不是1/0
        for (int i = 0; i < list.size(); i++) {
            Employee emp = list.get(i);
            emp.setSerialNumber(i + 1);
            // 确保性别显示为"男"/"女"
            if ("0".equals(emp.getGender())) {
                emp.setGender("男");
            } else if ("1".equals(emp.getGender())) {
                emp.setGender("女");
            }
        }
        ExcelUtil<Employee> util = new ExcelUtil<Employee>(Employee.class);
        util.exportExcel(response, list, "培训人员管理数据");
    }

    /**
     * 获取培训人员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(employeeService.selectEmployeeById(id));
    }

    /**
     * 新增培训人员管理
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:add')")
    @Log(title = "培训人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Employee employee)
    {
        return toAjax(employeeService.insertEmployee(employee));
    }

    /**
     * 修改培训人员管理
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:edit')")
    @Log(title = "培训人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Employee employee)
    {
        return toAjax(employeeService.updateEmployee(employee));
    }

    /**
     * 删除培训人员管理
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:remove')")
    @Log(title = "培训人员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(employeeService.deleteEmployeeByIds(ids));
    }

    /**
     * 验证员工姓名和手机号
     */
    @PreAuthorize("@ss.hasPermi('employeeManagement:employeeManagement:query')")
    @PostMapping(value = "/validateEmployee")
    public AjaxResult validateEmployee(@RequestBody Map<String, String> request) {
        String employeeName = request.get("employeeName");
        String phone = request.get("phone");

        // 先通过手机号查找员工
        Employee employee = employeeService.selectEmployeeByPhone(phone);

        if (employee == null) {
            return AjaxResult.error("公司无此员工，请输入正确的手机号");
        }

        // 检查姓名是否匹配
        if (!employee.getEmpName().equals(employeeName)) {
            Map<String, Object> result = new HashMap<>();
            result.put("employee", employee);
            result.put("nameMismatch", true);
            result.put("message", String.format("您输入的姓名\"%s\"与系统中该手机号对应的员工姓名不一致",
                    employeeName, employee.getEmpName()));
            return AjaxResult.success("姓名不匹配", result);
        }

        // 姓名和手机号都匹配
        return AjaxResult.success("验证通过", employee);
    }

}
